package com.gjx.leetcode;

//59. 螺旋矩阵 II
//
//给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。
//
//示例:
//
//输入: 3
//输出:
//[
// [ 1, 2, 3 ],
// [ 8, 9, 4 ],
// [ 7, 6, 5 ]
//]


public class Solution059 {
	public int[][] generateMatrix(int n) {
        
		if (n < 0) {
			return null;
		} else if (n == 0) {
			return new int[n][n];
		}
		
		int[][] res = new int[n][n];
		
		int left = 0;
		int right = n-1;
		int up = 0;
		int down = n-1;
		
		int v = 1;
		
		while (left <= right && up <= down) {
			
			for (int j=left; j<=right; j++) {
				res[up][j] = v++;
			}
			
			up++;
			
			if (left > right || up > down) {
				break;
			}
			
			for (int i=up; i<=down; i++) {
				res[i][right] = v++;
			}
			
			right--;
			
			if (left > right || up > down) {
				break;
			}
			
			for (int j=right; j>=left; j--) {
				res[down][j] = v++;
			}
			
			down--;
			
			if (left > right || up > down) {
				break;
			}
			
			for (int i=down; i>=up; i--) {
				res[i][left] = v++;
			}
			
			left++;
		}
		
		return res;
    }
}
